package com.mzpai.web.controller;

import java.net.SocketException;
import java.util.UUID;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.gexin.fastjson.JSONObject;
import com.mzpai.product.model.SystemAdmin;
import com.mzpai.product.model.SystemStore;
import com.mzpai.product.service.ShippingConfigService;
import com.mzpai.product.service.SystemAdminService;
import com.mzpai.product.service.SystemStoreService;
import com.mzpai.product.vo.SystemAdminVo;
import com.mzpai.product.vo.SystemStoreVo;
import com.mzpai.util.DateUtil;
import com.mzpai.util.MsgUtils;
import com.mzpai.util.RedisUtil;
import com.mzpai.util.StringUtils;
import com.mzpai.vo.ResponseVo;

import cn.hutool.core.bean.BeanUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * 用户登录，注册接口
 * @author yanglijun
 */

@Api(value = "用户登录注册接口")
@RestController
@RequestMapping("/login")
public class LoginController extends BaseController{
	@Autowired 
	private SystemAdminService systemAdminService;
	@Autowired 
	private SystemStoreService systemStoreService;
	@Autowired
	private StringRedisTemplate redisTemplate;
	@Autowired 
	private ShippingConfigService shippingConfigService;
	@Value("${mzpai.share.storeUrl}")
	private String shareStoreUrl;
	private static Logger log = LoggerFactory.getLogger(LoginController.class);

	@ApiOperation(value = "根据手机号，发送验证码")
	@RequestMapping(value = "/sendMsgCode")
	public ResponseVo<Boolean> sendMsgCode(@RequestParam(value = "sim", required = true) String sim) throws Exception {
		ResponseVo<Boolean> res = new ResponseVo<Boolean>();
		if(StringUtils.isBlank(sim)) {
			res.setCode(0);
			res.setMessage("请输入手机号！");
			return res;
		}
		String msgCode = StringUtils.getVerificationCode(4);
		if("18810189361".equals(sim)) {
			msgCode = "1234";
		}
		log.info("msg=输入手机号码={}， 验证码={}", sim, msgCode);
		//new RedisUtil(redisTemplate).set(sim + "-reg", msgCode, 60 * 3);
		new RedisUtil(redisTemplate).set(sim + "-reg", msgCode);
		/**发送短信*/
		MsgUtils.sendMsg(sim, msgCode);
		res.setCode(200);
		res.setMessage("发送成功！");
		return res;
	}
	
	@ApiOperation(value = "登录，手机号码，就返回用户信息；没有就创建用户信息！")
	@RequestMapping(value = "/register")
	public ResponseVo<SystemAdminVo> register(@RequestParam(value = "sim", required = true) String sim, 
			@RequestParam(value = "msgCode", required = true) String msgCode) throws Exception {
		logger.info("msg1=登录参数：手机号={}， 验证码{}", sim, msgCode);
		ResponseVo<SystemAdminVo> res = new ResponseVo<SystemAdminVo>();
		String redisCode =  new RedisUtil(redisTemplate).get(sim + "-reg")  + "";
		if(!msgCode.equals(redisCode) ) {
			res.setCode(0);
			res.setMessage("验证码错误！");
			return res;
		}
		/**登录，手机号码，就返回用户信息；没有就创建用户信息*/
		SystemAdmin adminUser = systemAdminService.queryBySim(sim);
		SystemAdminVo vo = new SystemAdminVo();
		if(adminUser == null) {
			//注册
			addSystemAdmin(sim);
			adminUser = systemAdminService.queryBySim(sim);
		}
		BeanUtil.copyProperties(adminUser, vo);
		vo.setProductSize(0);
		/**如果storeid ！= 0 代表有门店 */
		if(!"0".equals(adminUser.getStoreId())) {
			SystemStore store = systemStoreService.queryById(adminUser.getStoreId());
			SystemStoreVo storeVo = new SystemStoreVo();
			BeanUtil.copyProperties(store, storeVo);
			storeVo.setStoreUrl(shareStoreUrl + adminUser.getStoreId());
			vo.setStoreVo(storeVo);
			vo.setProductSize(store.getProductSize());
			//设置快递包邮金额
			vo.setShippingAmount(shippingConfigService.getShippingAmount(adminUser.getStoreId()));
		}
		String token = UUID.randomUUID().toString().replace("-", "");
		vo.setToken(token);
		new RedisUtil(redisTemplate).set(token, JSON.toJSON(vo));
		res.setCode(200);
		res.setMessage("成功");
		res.setResult(vo);
		return res;
				
	}
	
	
	@ApiOperation(value = "根据token，查询用户登录信息！")
	@RequestMapping(value = "/getSystemAdminByToken")
	public ResponseVo<SystemAdminVo> getSystemAdminByToken(@RequestParam(value = "token", required = true) String token) throws Exception {
		logger.info("msg1=登录参数：token={}", token);
		ResponseVo<SystemAdminVo> res = new ResponseVo<SystemAdminVo>();
		if(StringUtils.isBlank(token) ) {
			res.setCode(0);
			res.setMessage("token信息为空！");
			return res;
		}
		String temp = new RedisUtil(redisTemplate).get(token) + "";
		if(StringUtils.isBlank(temp)) {
			res.setCode(0);
			res.setMessage("token无效！");
			return res;
		}
		SystemAdminVo vo = JSONObject.parseObject(temp, SystemAdminVo.class);;
		res.setCode(200);
		res.setMessage("成功");
		res.setResult(vo);
		return res;
				
	}


	private int addSystemAdmin(String sim) throws SocketException {
		SystemAdmin o = new  SystemAdmin();
		o.setAccount(sim);
		o.setPwd(DigestUtils.md5DigestAsHex("123456".getBytes()));
		o.setRealName("小伙伴");
		o.setRoles("2");
		o.setLastIp(StringUtils.getRealIp());
		int nowTime = DateUtil.getUTCTime(null).intValue();
		o.setLastTime(nowTime);
		o.setAddTime(nowTime);
		o.setStoreId("0");
		return systemAdminService.save(o);
	}
}
